import { AuthFuncMenu } from "@/api/interface/auth/funcMenu";
import { childrenProps } from "@/components/ProForm/interface";
import { customTable } from "@/components/ProTable/interface";
import { ProTableValue } from "@/interface/public";

import { DrawerDataProps } from "@/hooks/use-drawer";
import { renderRowInput, renderRowSelect, renderRowSelectIcon } from "@/utils/render";

/**
 * @name 菜单配置
 */

interface gatherChildrenProps {
  iconOp: childrenProps[];
  componentOp: childrenProps[];
  setJsonOp: childrenProps[];
  pidOp: childrenProps[];
  roleKeyOp: Array<any>;
}
export function useDataGrid(
  proTableBox: ProTableValue,
  drawerData?: DrawerDataProps["drawerData"] | null,
  detailData?: customTable | null,
  detailDataRef?: ProTableValue
) {
  let gatherChildren = ref<gatherChildrenProps>({
    iconOp: [],
    componentOp: [],
    setJsonOp: [],
    pidOp: [],
    roleKeyOp: [
      {
        label: "测试权限",
        value: "测试权限"
      },
      {
        label: "权限",
        value: "测试权限"
      }
    ]
  });

  // 新增字段
  let form = {
    systemCode: "",
    path: "",
    name: "",
    redirect: "",
    component: "",
    icon: "",
    title: "",
    activeMenu: "",
    flagLink: "",
    flagHide: 0,
    flagFull: 0,
    flagAffix: 0,
    flagKeepAlive: 0,
    roleKey: "",
    pid: "",
    showOrder: "",
    remark: "",
    componentOp: [],
    iconOp: [],
    setJsonOp: [],
    pidOp: [],
    systemCodeOp: systemCodeOp(),
    roleKeyOp: gatherChildren.value.roleKeyOp,
    flagLinkOp: status3(),
    flagHideOp: status3(),
    flagFullOp: status3(),
    flagAffixOp: status3(),
    flagKeepAliveOp: status3()
  };

  // 获取选择值
  const getChildren = async (db?: Function) => {
    const arr: any = await promiseAllApi([
      funcDicFindByIcon(),
      funcDicFindByPath(),
      funcDicFindBySet(),
      funcMenuFindBySystem({ id: "mes" })
    ]);
    const a0 = changeArrField(arr[0], "title", "value");
    const a1 = changeArrField(arr[1], "title", "value");
    const a2 = changeArrField(arr[2], "title", "title");
    const a3 = changeArrField(arr[3], "path", "id");
    a3.unshift({
      label: "全部",
      value: 0
    });
    gatherChildren.value.iconOp = a0;

    gatherChildren.value.componentOp = a1;
    gatherChildren.value.setJsonOp = a2;
    gatherChildren.value.pidOp = a3;

    db && db();
    return {
      iconOp: a0,
      componentOp: a1,
      setJsonOp: a2,
      pidOp: a3,
      pid: drawerData?.row.id ? drawerData?.row.id : 0
    };
  };

  // 是否可编辑
  const isEdit = (row: AuthFuncMenu.ResSearch) => row.status === 0;

  let dataGrid = reactive<customTable>({
    initParam: {
      id: "MES"
    },
    // 表格配置项
    columns: [
      { prop: "operation", label: "operation", fixed: "left", width: 160 },
      {
        label: "系统名称",
        prop: "systemCode",
        width: 100,
        render: scope =>
          renderRowSelect(scope, "systemCode", "systemCodeOp", "系统名称", submitForm, () => null, "systemCode", isEdit),
        required: true
      },
      {
        label: "路由菜单访问路径",
        prop: "path",
        width: 160,
        render: scope => renderRowInput(scope, "path", "路由菜单访问路径", submitForm, isEdit),
        required: true
      },
      {
        label: "路由名称",
        prop: "name",
        width: 160,
        render: scope => renderRowInput(scope, "name", "路由name", submitForm, isEdit),
        required: true
      },
      {
        label: "视图文件路径",
        prop: "component",
        width: 160,
        render: scope =>
          renderRowSelect(scope, "component", "componentOp", "视图文件路径", submitForm, () => null, "component", isEdit),
        required: true
      },
      {
        label: "图标",
        prop: "icon",
        width: 160,
        render: scope => renderRowSelectIcon(scope, "icon", "iconOp", "图标", submitForm, () => null, "icon", isEdit),
        required: true
      },
      {
        label: "菜单标题",
        prop: "title",
        width: 160,
        render: scope => renderRowInput(scope, "title", "菜单标题", submitForm, isEdit),
        required: true
      },
      {
        label: "访问权限",
        width: 160,
        prop: "roleKey",
        render: scope => renderRowSelect(scope, "roleKey", "roleKeyOp", "访问权限", submitForm, () => null, "roleKey", isEdit)
      },
      {
        label: "父级",
        width: 160,
        prop: "pid",
        render: scope => renderRowSelect(scope, "pid", "pidOp", "父级", submitForm, () => null, "pid", isEdit)
      },
      {
        label: "id",
        width: 160,
        prop: "id",
        render: scope => renderRowInput(scope, "id", "id", submitForm, isEdit)
      },
      {
        label: "JSON配置字段",
        width: 160,
        prop: "setJson",
        render: scope => renderRowSelect(scope, "setJson", "setJsonOp", "JSON配置字段", submitForm, () => null, "setJson", isEdit)
      },
      {
        label: "路由重定向地址",
        prop: "redirect",
        width: 160,
        render: scope => renderRowInput(scope, "redirect", "路由重定向地址", submitForm, isEdit)
      },
      {
        label: "高亮的菜单",
        prop: "activeMenu",
        width: 160,
        render: scope => renderRowInput(scope, "activeMenu", "高亮的菜单", submitForm, isEdit)
      },
      {
        label: "路由外链访问地址",
        prop: "flagLink",
        width: 160,
        render: scope => renderRowInput(scope, "flagLink", "路由外链访问地址", submitForm, isEdit)
      },
      {
        width: 160,
        label: "是否在菜单中隐藏",
        prop: "flagHide",
        render: scope =>
          renderRowSelect(scope, "flagHide", "flagHideOp", "是否在菜单中隐藏", submitForm, () => null, "flagHide", isEdit)
      },
      {
        label: "菜单是否全屏",
        width: 160,
        prop: "flagFull",
        render: scope =>
          renderRowSelect(scope, "flagFull", "flagFullOp", "菜单是否全屏", submitForm, () => null, "flagFull", isEdit)
      },
      {
        label: "是否固定在标签页中",
        width: 160,
        prop: "flagAffix",
        render: scope =>
          renderRowSelect(scope, "flagAffix", "flagAffixOp", "是否固定在标签页中", submitForm, () => null, "flagAffix", isEdit)
      },
      {
        label: "路由是否缓存",
        width: 160,
        prop: "flagKeepAlive",
        render: scope =>
          renderRowSelect(
            scope,
            "flagKeepAlive",
            "flagKeepAliveOp",
            "路由是否缓存",
            submitForm,
            () => null,
            "flagKeepAlive",
            isEdit
          )
      },

      {
        label: "备注",
        prop: "remark",
        render: scope => renderRowInput(scope, "remark", "备注", submitForm, isEdit)
      }
    ],
    headButtonList: [
      {
        label: "新增",
        type: "primary",
        icon: "Plus",
        methods: () => add()
      }
    ],
    rowButtonList: [
      // {
      //   label: "",
      //   type: "danger",
      //   icon: "svg-del",
      //   tooltip: "删除",
      //   hide: row => isAddFlag && row.status === 0,
      //   methods: (row: AuthFuncMenu.ResSearch) => {
      //     const params = { id: row.id };
      //     useHandleData(funcMenuRemove, params, `删除菜单标题 【${row.title}】 数据`, proTableBox.value?.getTableList);
      //   },
      //   attrs: {
      //     link: true
      //   }
      // },
      {
        label: "",
        type: "primary",
        tooltip: "启用",
        icon: "svg-start2",
        hide: row => row.status === 1 && row?.isAddFlag !== "true",
        methods: (row: AuthFuncMenu.ResSearch) => {
          const params = { id: row.id };
          useHandleData(
            funcMenuEnable,
            params,
            `${transitionLanguages("table", "启用")}【${row.title}】`,
            proTableBox.value?.getTableList
          );
        },
        attrs: {
          link: true
        }
      },
      {
        label: "",
        type: "danger",
        icon: "svg-disable",
        tooltip: "禁用",
        hide: row => row.status === 0 && row?.isAddFlag !== "true",
        methods: (row: AuthFuncMenu.ResSearch) => {
          const params = { id: row.id };
          useHandleData(
            funcMenuDisable,
            params,
            `${transitionLanguages("table", "禁用")}【${row.title}】`,
            proTableBox.value?.getTableList
          );
        },
        attrs: {
          link: true
        }
      }
    ]
  });

  /**
   * @description: 表单提交
   * @return {*}
   */
  const submitForm = async () => {
    let form: AuthFuncMenu.ReqSave;
    if (detailDataRef) {
      form = detailDataRef.value?.tableData.find(item => item.isAddFlag || item["edit"]);
    } else {
      form = proTableBox.value?.tableData.find(item => item.isAddFlag || item["edit"]);
    }
    if (!form) return;
    if (form.id === form.pid) {
      elMessage("父级id不能是本身", "warning");
      return;
    }

    await funcMenuSave(form);
    // 更新修改后的表格参数
    getChildren();
    elMessage("操作成功");
    proTableBox.value?.getTableList();
  };

  const dataCallBack = (data: AuthFuncMenu.ResSearch[]) => {
    data = data.map(item => {
      const { childrenList } = item;
      if (drawerData?.row?.id && detailData) {
        detailData.data = childrenList?.map(son => {
          const newSon = setBackData(son);
          return newSon;
        });
      }
      const newItem = setBackData(item);
      return newItem;
    });

    return data;
  };

  const setBackData = (item: AuthFuncMenu.ResSearch) => {
    const { setJsonOp, roleKeyOp, iconOp, componentOp, pidOp } = gatherChildren.value;
    const op = status3();
    return {
      ...item,
      componentOp: componentOp,
      iconOp: iconOp,
      setJsonOp: setJsonOp,
      pidOp: pidOp,
      systemCodeOp: systemCodeOp(),
      roleKeyOp: roleKeyOp,
      flagLinkOp: op,
      flagHideOp: op,
      flagFullOp: op,
      flagAffixOp: op,
      flagKeepAliveOp: op
    };
  };

  /**
   * @description: 表格增加钩子
   * @return {*}
   */
  const { isAddFlag, requiredField, add, tableBasicBtn } = useTableAdd(
    dataGrid.columns,
    detailDataRef || proTableBox,
    form,
    submitForm,
    getChildren
  );
  onBeforeMount(() => {
    const str =
      "systemCode,path,name,redirect,component,icon,title,activeMenu,flagLink,flagHide,flagFull,flagAffix,flagKeepAlive,roleKey,showOrder,remark,systemCodeOp,componentOp,iconOp,roleKeyOp,flagLinkOp,flagHideOp,flagFullOp,pidOp,flagAffixOp,flagKeepAliveOp,setJsonOp,pid";
    dataGrid.rowButtonList?.unshift(...tableBasicBtn(str, isEdit));
    getChildren(() => {
      proTableBox.value?.getTableList();
    });
  });

  const cellClick = (row: AuthFuncMenu.ResSearch) => {
    if (drawerData && detailData) {
      drawerData.row = row;
      detailData.data = row.childrenList?.map(son => {
        const newSon = setBackData(son);
        return newSon;
      });
    }
  };

  return {
    dataGrid,
    dataCallBack,
    cellClick,
    isAddFlag,
    requiredField
  };
}
